package com.hutiao.snowhb.actions.mm;

import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.hutiao.snowhb.common.SimsimiClient;
import com.hutiao.snowhb.entities.SnowMMChat;
import com.hutiao.snowhb.entities.WeixinUserInfo;
import com.hutiao.snowhb.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/snowmm")
public class SnowMMChatAction extends ActionSupport {

	private static final long serialVersionUID = -9058367301764373682L;
	
	private static Logger logger = Logger.getLogger(SnowMMChatAction.class);
	
	@Autowired
	private UserService userService;
	
	private String visitorId;
	
	private WeixinUserInfo visitor;
	
	private String message;
	
	private SnowMMChat respChat;

	@JSON(serialize=false)
	public String getVisitorId() {
		return visitorId;
	}

	public void setVisitorId(String visitorId) {
		this.visitorId = visitorId;
	}

	@JSON(serialize=false)
	public WeixinUserInfo getVisitor() {
		return visitor;
	}

	public void setVisitor(WeixinUserInfo visitor) {
		this.visitor = visitor;
	}

	@JSON(serialize=false)
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public SnowMMChat getRespChat() {
		return respChat;
	}

	public void setRespChat(SnowMMChat respChat) {
		this.respChat = respChat;
	}

	@Action(value="mm_chat")
	public String mmChat() throws Exception {
		
		this.visitor = this.userService.getWxUserInfo(this.visitorId);
		
		return SUCCESS;
	}
	
	@Action(value="mm_chat_init",results = { @Result(type = "json") })
	public String initChat() {
		
		this.respChat = new SnowMMChat();
		this.respChat.setResponse("您好，我是雪花妹，有什么开心的事想跟我说吗？");
		this.respChat.setVirtualMM(this.userService.virtualMM());
		this.respChat.setResult("success");
		
		return SUCCESS;
	}
	
	@Action(value="mm_chat_send",results = { @Result(type = "json") })
	public String sendMessage() throws UnsupportedEncodingException {
		
		String response = "呵呵";
		
		try {
			// simsimi机器人处理
			response = SimsimiClient.chat(this.message);
			//String response = this.message;
		} catch (Exception e) {
			logger.error("Exception", e);	
		}
		
		this.respChat = new SnowMMChat();
		this.respChat.setResponse(response);
		this.respChat.setVirtualMM(this.userService.virtualMM());
		this.respChat.setResult("success");
		
		return SUCCESS;
	}

}
